using System.Collections.Generic;
using System.Data;
using EmailContacts.ServiceModel;
using EmailContacts.ServiceModel.Types;
using ServiceStack;
using ServiceStack.FluentValidation;
using ServiceStack.OrmLite;

namespace EmailContacts.ServiceInterface
{
    public class ContactsValidator : AbstractValidator<CreateContact>
    {
        public ContactsValidator()
        {
            RuleFor(x => x.Name).NotEmpty().WithMessage("A Names is what's needed.");
            RuleFor(x => x.Email).NotEmpty().EmailAddress();
            RuleFor(x => x.Age).GreaterThan(0);
        }
    }

    public class ContactsServices : Service
    {
        public object Any(GetContact request)
        {
            return Db.SingleById<Contact>(request.Id);
        }
        
        public IList<Contact> Any(FindContacts request)
        {
            return request.Age.HasValue
                ? Db.Select<Contact>(q => q.Age == request.Age)
                : Db.Select<Contact>();
        }

        public Contact Post(CreateContact request)
        {
            var contact = request.ConvertTo<Contact>();
            Db.Save(contact);
            return contact;
        }

        public void Any(DeleteContact request)
        {
            Db.DeleteById<Contact>(request.Id);
        }

        public void Any(Reset request)
        {
            Db.DeleteAll<Email>();
            Db.DeleteAll<Contact>();
            
            AddContacts(Db);
        }

        public static void AddContacts(IDbConnection db)
        {
            db.InsertAll(new List<Contact>
            {
                new Contact {Name = "451649157", Email = "451649157@qq.com", Age = 29},
                new Contact {Name = "daves2009", Email = "daves2009@126.com", Age = 29},
                new Contact {Name = "jhoneleeo", Email = "jhoneleeo@gmail.com", Age = 29}
            });
        }
    }
}